package cn.tiga.org.service.impl;

import cn.tiga.basic.service.impl.BaseServiceImpl;
import cn.tiga.org.domain.Department;
import cn.tiga.org.mapper.DepartmentMapper;
import cn.tiga.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    public void add(Department departmant) {
        departmentMapper.add(departmant);
        //在调用修改UPdate修改字段
        update(departmant);
    }

    @Override
    public void update(Department departmant) {
        // 因为前端没有dirpath上级部门字段 所以上级字段需要手动拼接后在设置回去
        if (departmant.getParent_id() == null) {
            Long id = departmant.getId();
            // 拼接dirpath
            departmant.setDirPath("/" + id);
        } else {
            // 如果不是就获取它的父亲ID
            Long parent_id = departmant.getParent_id();
            // 通过父亲ID查找他的父亲的diapath
            Department department = departmentMapper.loadById(parent_id);
            // 拼接父亲的ID和自己的ID重新设置到DIrPath中去
            departmant.setDirPath(department.getDirPath() + "/" + department.getId());
        }
        departmentMapper.update(departmant);
    }


    @Override
    public List<Department> deptTree() {
        // 查询这个的全部
        List<Department> departments = departmentMapper.loadAll();
        // 创建一个新集合装入id
        Map<Long, Department> allMap = departments.stream().collect(Collectors.toMap(Department::getId, item -> item));
        // 遍历获取到的每个数据 获取ID判断它是否为空
        List<Department> depts = new ArrayList<>();
        for (Department pare : departments) {
            if (pare.getParent_id() == null) {
                depts.add(pare);
            } else {
                Department department = allMap.get(pare.getParent_id());
                if (department != null) {
                    department.getChildren().add(pare);
                }
            }
        }

        return depts;
    }
}
